<template>
    <div class="smart-screen">
      <div class="bg-decoration">
        <div class="left-decoration"></div>
        <div class="center-decoration">朗歌斯 - 自动生产线看板</div>
        <div class="right-decoration"></div>
      </div>
      <div class="header">
        <div class="time">{{ currentTime }}</div>
      </div>
      
      <div class="content">
        <div class="left-section">
          <div class="chart-box">
            <h3>一周不良品统计</h3>
            <div ref="weeklyDefectChartRef" class="chart"></div>
          </div>
          
          <div class="chart-box">
            <h3>关键工序</h3>
            <div ref="keyProcessChartRef" class="chart"></div>
          </div>
          
          <div class="chart-box">
            <h3>一周产量均差</h3>
            <div ref="weeklyOutputChartRef" class="chart"></div>
          </div>
        </div>
        
        <div class="center-section">
          <div class="chart-box">
            <h3>订单总体进度</h3>
            <div ref="totalProgressChartRef" class="chart"></div>
            <div class="progress-info">
              <p>总体计划<span>{{ totalPlan }}</span></p>
              <p>已生产<span>{{ produced }}</span></p>
              <p>不良品<span>{{ defects }}</span></p>
              <p>完成率<span>{{ completionRate }}%</span></p>
            </div>
          </div>
          
          <div class="chart-box">
            <h3>近期生产计划列表</h3>
            <div class="scroll-table-container">
              <table class="plan-table">
                <thead>
                  <tr>
                    <th>订单号</th>
                    <th>计划数量</th>
                    <th>计划开始时间</th>
                    <th>计划结束时间</th>
                    <th>订单状态</th>
                    <th>完成率</th>
                  </tr>
                </thead>
                <tbody ref="scrollBody">
                  <tr v-for="item in productionPlanList" :key="item.id">
                    <td class="order-id">{{ item.orderId }}</td>
                    <td>{{ item.planQuantity }}</td>
                    <td>{{ item.startTime }}</td>
                    <td>{{ item.endTime }}</td>
                    <td>
                      <span :class="['status', item.status]">{{ item.statusText }}</span>
                    </td>
                    <td>{{ item.completionRate }}%</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
        
        <div class="right-section">
          <div class="chart-box">
            <h3>订单今日进度</h3>
            <div ref="dailyProgressChartRef" class="chart"></div>
            <div class="progress-info">
              <p data-value="今日计划">今日计划 <span>{{ currentDailyPlan.planQuantity }}</span></p>
              <p data-value="已经生产">已经生产 <span>{{ currentDailyPlan.produced }}</span></p>
              <p data-value="不良品">不良品 <span>{{ currentDailyPlan.defects }}</span></p>
              <p data-value="良品率">良品率 <span>{{ currentDailyPlan.qualityRate }}%</span></p>
            </div>
          </div>
          
          <div class="info-box">
            <h3>当前班组</h3>
            <div class="team-info" :style="teamInfoStyle">
              <p>名称: <span>{{ currentTeam.teamName }}</span></p>
              <p>人数: <span>{{ currentTeam.teamNum }}</span></p>
              <p>负责人: <span>{{ currentTeam.duty }}</span></p>
              <p>电话: <span>{{ currentTeam.phone }}</span></p>
            </div>
          </div>
          
          <div class="chart-box exception-list">
            <h3>异常列表</h3>
            <div class="scroll-list">
              <div v-for="item in exceptionList" :key="item.id" class="exception-item">
                <span class="time">{{ item.time }}</span>
                <span class="type">{{ item.type }}</span>
                <span class="description">{{ item.description }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
  import * as echarts from 'echarts'
  import http from '@/api/http'
  
  // 时间显示
  const currentTime = ref('')
  const updateTime = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    currentTime.value = `${year}年${month}月${day}日-${hours}时${minutes}分${seconds}秒`
  }
  
  let timer: number
  let teamInfoTimer: number
  let teamRotationTimer: number
  let dailyPlanTimer: number
  
  // 图表DOM引用
  const dailyProgressChartRef = ref<HTMLElement | null>(null)
  const weeklyDefectChartRef = ref<HTMLElement | null>(null)
  const keyProcessChartRef = ref<HTMLElement | null>(null)
  const weeklyOutputChartRef = ref<HTMLElement | null>(null)
  
  // 图表实例
  let dailyProgressChart: echarts.ECharts | null = null
  let weeklyDefectChart: echarts.ECharts | null = null
  let keyProcessChart: echarts.ECharts | null = null
  let weeklyOutputChart: echarts.ECharts | null = null
  
  // 添加新的数据存储
  const allDailyPlans = ref<any[]>([])
  const currentPlanIndex = ref(0)
  
  // 图表引用
  const totalProgressChartRef = ref<HTMLElement | null>(null)
  let totalProgressChart: echarts.ECharts | null = null
  
  // 订单总体进度数据
  const totalPlan = ref<number>(0)      // 当日计划产量 (yield)
  const produced = ref<number>(0)       // 当日实际产量 (actual)
  const defects = ref<number>(0)        // 当日次品数量 (defective)
  const completionRate = ref<number>(0)  // 一次通过率 (passRate)
  
  // 定时器
  let progressTimer: number | null = null
  let dataFetchTimer: number | null = null
  // 当前显示的数据索引
  let currentDataIndex = 0
  // 存储所有数据
  const allProgressData = ref<any[]>([])
  
  // 生产计划列表数据
  const productionPlanList = ref<any[]>([])
  let planListTimer: number | null = null
  
  onMounted(() => {
    console.log('组件挂载，初始化图表和定时器')
    updateTime()
    timer = setInterval(updateTime, 1000)
    
    // 初始化图表
    nextTick(() => {
      if (totalProgressChartRef.value) {
        totalProgressChart = echarts.init(totalProgressChartRef.value)
      }
      initCharts()
      initDailyProgressChart()
      // 启动定时器
      startTimer()
    })
    
    // 初始获取数据
    getCurrentTeam()
    getDailyProgress()
    getProductionPlanList()
    getProgressData() // 获取总体进度数据
    
    // 设置定时器
    teamInfoTimer = setInterval(getCurrentTeam, 30000) // 每30秒更新一次班组信息
    teamRotationTimer = setInterval(switchToNextTeam, 5000) // 每5秒切换一次班组
    
    // 修改数据更新定时器逻辑
    dailyPlanTimer = setInterval(() => {
      if (new Date().getSeconds() % 10 === 0) { // 每10秒获取一次新数据
        getDailyProgress()
        getProductionPlanList()
      } else { // 其他时间只进行数据轮换
        updateCurrentPlanData()
      }
    }, 5000) // 每5秒执行一次
    
    // 启动表格滚动
    autoScroll()
    
    // 启动生产计划列表定时器
    startPlanListTimer()
  })
  
  onUnmounted(() => {
    console.log('组件卸载，清理资源')
    if (timer) clearInterval(timer)
    if (teamInfoTimer) clearInterval(teamInfoTimer)
    if (teamRotationTimer) clearInterval(teamRotationTimer)
    if (dailyPlanTimer) clearInterval(dailyPlanTimer)
    if (planListTimer) clearTimeout(planListTimer)
    if (progressTimer) {
      clearInterval(progressTimer)
      progressTimer = null
    }
    if (dataFetchTimer) {
      clearInterval(dataFetchTimer)
      dataFetchTimer = null
    }
    
    // 销毁图表实例
    if (dailyProgressChart) {
      dailyProgressChart.dispose()
      dailyProgressChart = null
    }
    if (totalProgressChart) {
      totalProgressChart.dispose()
      totalProgressChart = null
    }
    // 移除事件监听
    window.removeEventListener('resize', () => {
      totalProgressChart?.resize()
    })
    
    // 清理生产计划列表定时器
    if (planListTimer) {
      clearInterval(planListTimer)
      planListTimer = null
    }
  })
  
  // 定义接口
  interface TeamData {
    id: number
    teamName: string
    teamNum: number
    duty: string
    phone: string
    createTime: string
  }
  
  // 定义每日计划接口
  interface DailyPlan {
    dailyId: number
    planCode: string
    orderCode: string
    line: string
    targetTime: string
    yield: number        // 当日计划产量
    actual: number       // 当日实际产量
    defective: number    // 当日次品数量
    passRate: number     // 一次通过率
    actualTake: number   // 每件实际耗时
    team: string
    morningshiftStarttim: string
    morningshiftEndtime: string
    firstmorningShiftStarttime: string
    firstmorningShiftEndtime: string
    middleShiftStartTime: string
    middleShiftEndTime: string
    firstmiddleShiftStarttim: string
    firstmiddleShiftEndTime: string
    eveningShiftStartTime: string
    eveningShiftEndTime: string
    firsteveningShiftStartTime: string
    firsteveningShiftEndTime: string
    calibratedTimePerPiece: number
    actualTimePerPiece: number
  }
  
  // 今日进度数据
  const dailyPlan = ref<DailyPlan[]>([])
  const currentDailyPlan = ref({
    planQuantity: 0,    // 今日计划
    produced: 0,        // 已经生产
    defects: 0,         // 不良品
    qualityRate: 0      // 良品率
  })
  
  // 当前班组信息
  const currentTeam = ref<TeamData>({
    id: 0,
    teamName: '',
    teamNum: 0,
    duty: '',
    phone: '',
    createTime: ''
  })
  
  // 存储所有班组信息
  const allTeams = ref<TeamData[]>([])
  // 当前显示的班组索引
  const currentTeamIndex = ref(0)
  
  // 切换到下一个班组
  const switchToNextTeam = () => {
    if (allTeams.value.length > 0) {
      currentTeamIndex.value = (currentTeamIndex.value + 1) % allTeams.value.length
      currentTeam.value = allTeams.value[currentTeamIndex.value]
    }
  }
  
  // 获取当前班组信息
  const getCurrentTeam = () => {
    console.log('开始获取班组信息...')
    http.get('/api/SmartLargeScreen/GetTeamledger').then((res: any) => {
      console.log('获取到的班组数据:', res)
      if (res && res.data && Array.isArray(res.data) && res.data.length > 0) {
        // 保存所有班组信息
        allTeams.value = res.data
        // 设置初始班组
        currentTeam.value = allTeams.value[currentTeamIndex.value]
        console.log('当前班组数据:', currentTeam.value)
      }
    }).catch((error) => {
      console.error('获取班组信息失败:', error)
      currentTeam.value = {
        id: 0,
        teamName: '暂无班组',
        teamNum: 0,
        duty: '暂无',
        phone: '暂无',
        createTime: ''
      }
      allTeams.value = []
    })
  }
  
  // 异常列表数据
  const exceptionList = ref([
    {
      id: 1,
      time: '2024-03-15 10:30',
      type: '设备故障',
      description: '2号生产线传送带卡死'
    },
    {
      id: 2,
      time: '2024-03-15 11:15',
      type: '质量异常',
      description: '产品尺寸超出规格范围'
    },
    {
      id: 3,
      time: '2024-03-15 14:20',
      type: '系统警告',
      description: '温度过高预警'
    }
  ])
  
  // 表格滚动效果
  const scrollBody = ref<HTMLElement>()
  let scrollTimer: number
  
  const startScroll = () => {
    if (!scrollBody.value) return
    
    const scrollStep = () => {
      if (!scrollBody.value) return
      if (scrollBody.value.scrollTop + scrollBody.value.clientHeight >= scrollBody.value.scrollHeight) {
        scrollBody.value.scrollTop = 0
      } else {
        scrollBody.value.scrollTop += 1
      }
    }
    
    scrollTimer = setInterval(scrollStep, 50)
  }
  
  // 初始化图表
  const initCharts = () => {
    // 一周不良品统计图表
    if (weeklyDefectChartRef.value) {
      weeklyDefectChart = echarts.init(weeklyDefectChartRef.value)
      weeklyDefectChart.setOption({
        grid: {
          top: 30,
          right: 30,
          bottom: 30,
          left: 50,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c}个'
        },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六'],
          axisLine: {
            lineStyle: {
              color: '#0a4cd1'
            }
          },
          axisLabel: {
            color: '#fff',
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#0a4cd1'
            }
          },
          axisLabel: {
            color: '#fff'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(10, 76, 209, 0.1)'
            }
          }
        },
        series: [{
          data: [4, 3, 2, 3, 5, 1],
          type: 'line',
          smooth: true,
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(0, 240, 255, 0.3)'
              }, {
                offset: 1,
                color: 'rgba(0, 240, 255, 0)'
              }]
            }
          },
          lineStyle: {
            color: '#00f0ff',
            width: 3
          },
          itemStyle: {
            color: '#00f0ff',
            borderWidth: 2
          },
          emphasis: {
            itemStyle: {
              borderWidth: 4
            }
          }
        }]
      })
    }
  
    // 关键工序图表
    if (keyProcessChartRef.value) {
      keyProcessChart = echarts.init(keyProcessChartRef.value)
      keyProcessChart.setOption({
        radar: {
          indicator: [
            { name: '压接端子', max: 100 },
            { name: '绕线', max: 100 },
            { name: '铆压', max: 100 },
            { name: '检测', max: 100 },
            { name: '包装', max: 100 }
          ],
          splitArea: {
            areaStyle: {
              color: ['rgba(0, 240, 255, 0.05)', 'rgba(0, 240, 255, 0.1)']
            }
          },
          axisLine: {
            lineStyle: {
              color: '#0a4cd1'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#0a4cd1'
            }
          },
          name: {
            textStyle: {
              color: '#fff'
            }
          }
        },
        series: [{
          type: 'radar',
          data: [{
            value: [90, 85, 95, 88, 92],
            name: '完成率',
            areaStyle: {
              color: 'rgba(0, 240, 255, 0.3)'
            },
            lineStyle: {
              color: '#00f0ff'
            },
            itemStyle: {
              color: '#00f0ff'
            }
          }]
        }]
      })
    }
  
    // 一周产量均差图表
    if (weeklyOutputChartRef.value) {
      weeklyOutputChart = echarts.init(weeklyOutputChartRef.value)
      weeklyOutputChart.setOption({
        grid: {
          top: 30,
          right: 30,
          bottom: 30,
          left: 50,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c}件'
        },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六'],
          axisLine: {
            lineStyle: {
              color: '#0a4cd1'
            }
          },
          axisLabel: {
            color: '#fff',
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#0a4cd1'
            }
          },
          axisLabel: {
            color: '#fff'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(10, 76, 209, 0.1)'
            }
          }
        },
        series: [{
          data: [1000, 200, 450, 400, 600, 100],
          type: 'bar',
          barWidth: '40%',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: '#00f0ff'
              }, {
                offset: 1,
                color: 'rgba(0, 240, 255, 0.1)'
              }]
            }
          }
        }]
      })
    }
  
    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      weeklyDefectChart?.resize()
      keyProcessChart?.resize()
      weeklyOutputChart?.resize()
      totalProgressChart?.resize()
      dailyProgressChart?.resize()
    })
  }
  
  // 自动滚动
  const autoScroll = () => {
    const scrollContainer = document.querySelector('.scroll-table-container') as HTMLElement;
    const tbody = document.querySelector('.plan-table tbody') as HTMLElement;
    if (!tbody || !scrollContainer) return;

    let currentPosition = 0;
    const rowHeight = 41; // 每行高度
    const scrollSpeed = 1; // 滚动速度
    const containerHeight = scrollContainer.clientHeight;
    let isHovered = false;

    // 初始化位置，从底部开始
    tbody.style.transform = `translateY(${containerHeight}px)`;

    tbody.addEventListener('mouseenter', () => {
      isHovered = true;
    });

    tbody.addEventListener('mouseleave', () => {
      isHovered = false;
    });

    function animate() {
      if (!isHovered) {
        currentPosition -= scrollSpeed; // 向上滚动是负值

        // 计算内容总高度
        const contentHeight = tbody.scrollHeight;
        
        // 当最后一行到达顶部时
        if (Math.abs(currentPosition) >= contentHeight + containerHeight) {
          // 重置位置到底部
          currentPosition = 0;
          tbody.style.transform = `translateY(${containerHeight}px)`;
        } else {
          // 从下往上滚动
          tbody.style.transform = `translateY(${containerHeight + currentPosition}px)`;
        }
      }
      requestAnimationFrame(animate);
    }

    requestAnimationFrame(animate);
  };
  
  // 添加过渡效果的样式
  const teamInfoStyle = computed(() => ({
    opacity: 1,
    transform: 'translateY(0)',
    transition: 'all 0.5s ease-in-out'
  }))

  // 更新今日进度图表
  const updateDailyProgressChart = () => {
    if (!dailyProgressChart || !dailyProgressChartRef.value) {
      return
    }

    const completed = currentDailyPlan.value.produced || 0
    const total = currentDailyPlan.value.planQuantity || 0
    const completionRate = total > 0 ? ((completed / total) * 100).toFixed(1) : '0.0'

    try {
      dailyProgressChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 20,
          top: 'center',
          textStyle: {
            color: '#fff'
          },
          data: ['已完成', '未完成']
        },
        series: [{
          type: 'pie',
          radius: ['65%', '80%'],
          center: ['30%', '50%'],
          label: {
            show: false
          },
          data: [{
            value: completed,
            name: '已完成',
            itemStyle: {
              color: '#52c41a'
            }
          }, {
            value: Math.max(0, total - completed),
            name: '未完成',
            itemStyle: {
              color: 'rgba(10, 76, 209, 0.3)'
            }
          }]
        }],
        graphic: [{
          type: 'text',
          left: '25%',
          top: 'middle',
          style: {
            text: '完成率',
            textAlign: 'center',
            fill: '#fff',
            fontSize: 14
          }
        }, {
          type: 'text',
          left: '25%',
          top: '55%',
          style: {
            text: completionRate + '%',
            textAlign: 'center',
            fill: '#52c41a',
            fontSize: 20,
            fontWeight: 'bold'
          }
        }]
      })
    } catch (error) {
      console.error('更新今日进度图表失败:', error)
    }
  }

  // 修改获取今日计划数据的函数
  const getDailyProgress = () => {
    console.log('开始获取今日进度数据...', new Date().toLocaleString())
    http.get('/api/SmartLargeScreen/GetDailyPlan').then((res: any) => {
      if (res && res.data && Array.isArray(res.data) && res.data.length > 0) {
        // 保存所有数据
        allDailyPlans.value = res.data
        // 更新当前显示的数据
        updateCurrentPlanData()
      }
    }).catch((error) => {
      console.error('获取今日进度数据失败:', error)
      resetDailyPlanData()
      allDailyPlans.value = []
      nextTick(() => {
        updateDailyProgressChart()
      })
    })
  }

  // 添加更新当前显示数据的函数
  const updateCurrentPlanData = () => {
    if (allDailyPlans.value.length === 0) {
      resetDailyPlanData()
      return
    }

    const currentPlan = allDailyPlans.value[currentPlanIndex.value]
    currentDailyPlan.value = {
      planQuantity: currentPlan.yield || 0,
      produced: currentPlan.actual || 0,
      defects: currentPlan.defective || 0,
      qualityRate: currentPlan.passRate || 0
    }

    console.log(`更新后的今日进度数据(第${currentPlanIndex.value + 1}条):`, currentDailyPlan.value)
    
    // 更新图表
    nextTick(() => {
      updateDailyProgressChart()
    })

    // 准备下一次更新的索引
    currentPlanIndex.value = (currentPlanIndex.value + 1) % allDailyPlans.value.length
  }

  // 修改获取生产计划列表的函数
  const getProductionPlanList = async () => {
    try {
      console.log('开始获取生产计划列表数据:', new Date().toLocaleString())
      const res = await http.get('/api/ProductionManagement/GetTicketLedgerList')
      
      if (res?.data && Array.isArray(res.data)) {
        // 使用 computed 处理数据，减少不必要的重复计算
        productionPlanList.value = res.data.map((item: any) => {
          const completionRate = item.plan > 0 ? Math.round((item.produce / item.plan) * 100) : 0
          const status = getOrderStatus(Number(item.ordersState))
          const ticketNumber = item.ticketNumber || item.tickeNumber || item.TicketNumber || ''
          
          return {
            id: item.ticketId || undefined,
            orderId: ticketNumber || '暂无订单号',
            planQuantity: Number(item.plan) || 0,
            startTime: item.stateTime || '',
            endTime: item.endTime || '',
            status: status.className,
            statusText: status.text,
            completionRate
          }
        })
      }
    } catch (error) {
      console.error('获取生产计划列表失败:', error)
      productionPlanList.value = []
    }
  }
  
  // 订单状态处理函数
  const getOrderStatus = (state: number) => {
    switch(state) {
      case 1:
        return { className: 'pending', text: '待生产' }
      case 2:
        return { className: 'processing', text: '进行中' }
      case 3:
        return { className: 'completed', text: '已完成' }
      default:
        return { className: 'pending', text: '待生产' }
    }
  }
  
  // 修改重置计划数据的函数
  const resetDailyPlanData = () => {
    currentDailyPlan.value = {
      planQuantity: 0,
      produced: 0,
      defects: 0,
      qualityRate: 0
    }
    currentPlanIndex.value = 0
    allDailyPlans.value = []
  }
  
  // 初始化今日进度图表
  const initDailyProgressChart = () => {
    if (!dailyProgressChartRef.value || dailyProgressChart) {
      return
    }
    
    try {
      dailyProgressChart = echarts.init(dailyProgressChartRef.value)
      updateDailyProgressChart()
    } catch (error) {
      console.error('初始化今日进度图表失败:', error)
    }
  }

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    if (dailyProgressChart) {
      dailyProgressChart.resize()
    }
  })

  // 监听数据变化
  watch(() => currentDailyPlan.value, () => {
    nextTick(() => {
      updateDailyProgressChart()
    })
  }, { deep: true })

  // 获取订单总体进度数据
  const getProgressData = async () => {
    try {
      console.log('开始获取订单总体进度数据:', new Date().toLocaleString())
      const res = await http.get('/api/SmartLargeScreen/GetDailyPlan')
      if (res?.data && Array.isArray(res.data) && res.data.length > 0) {
        // 保存所有数据
        allProgressData.value = res.data
        console.log('获取到新数据，共', allProgressData.value.length, '条')
      }
    } catch (error) {
      console.error('获取订单总体进度数据失败:', error)
    }
  }

  // 更新显示的数据
  const updateDisplayData = () => {
    if (allProgressData.value.length === 0) return

    // 获取当前索引的数据
    const currentData = allProgressData.value[currentDataIndex]
    
    // 更新显示的数据
    totalPlan.value = Number(currentData.yield)          // 当日计划产量
    produced.value = Number(currentData.actual)          // 当日实际产量
    defects.value = Number(currentData.defective)        // 当日次品数量
    completionRate.value = Number(currentData.passRate)  // 一次通过率

    console.log('更新显示数据，当前索引:', currentDataIndex)

    // 更新图表
    nextTick(() => {
      updateChart()
    })

    // 准备下一次显示的索引
    currentDataIndex = (currentDataIndex + 1) % allProgressData.value.length
  }

  // 更新图表
  const updateChart = () => {
    if (!totalProgressChart) return

    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'horizontal',
        right: 20,
        top: 10,
        textStyle: {
          color: '#fff'
        },
        data: ['已完成', '未完成']
      },
      series: [
        {
          name: '完成进度',
          type: 'pie',
          radius: ['65%', '80%'],
          center: ['50%', '50%'],
          label: {
            show: false
          },
          data: [
            {
              value: completionRate.value,
              name: '已完成',
              itemStyle: {
                color: '#00f0ff'
              }
            },
            {
              value: 100 - completionRate.value,
              name: '未完成',
              itemStyle: {
                color: 'rgba(10, 76, 209, 0.3)'
              }
            }
          ]
        }
      ],
      graphic: [
        {
          type: 'text',
          left: 'center',
          top: '40%',
          style: {
            text: '完成率',
            textAlign: 'center',
            fill: '#fff',
            fontSize: 14
          }
        },
        {
          type: 'text',
          left: 'center',
          top: '50%',
          style: {
            text: completionRate.value + '%',
            textAlign: 'center',
            fill: '#00f0ff',
            fontSize: 24,
            fontWeight: 'bold'
          }
        }
      ]
    }

    totalProgressChart.setOption(option)
  }

  // 清理所有定时器
  const clearAllTimers = () => {
    if (progressTimer) {
      clearInterval(progressTimer)
      progressTimer = null
    }
    if (dataFetchTimer) {
      clearInterval(dataFetchTimer)
      dataFetchTimer = null
    }
  }

  // 启动定时器
  const startTimer = () => {
    // 清理可能存在的旧定时器
    clearAllTimers()
    
    // 重置索引
    currentDataIndex = 0
    
    // 立即执行一次数据获取
    getProgressData().then(() => {
      // 获取到数据后立即显示第一条
      if (allProgressData.value.length > 0) {
        updateDisplayData()
      }
    })
    
    // 设置数据轮换定时器，每5秒切换显示
    progressTimer = setInterval(() => {
      updateDisplayData()
    }, 5000)
    
    // 设置数据获取定时器，每30秒更新一次数据
    dataFetchTimer = setInterval(() => {
      getProgressData()
    }, 30000)
    
    console.log('定时器已启动 - 数据轮换间隔：5秒，数据获取间隔：30秒')
  }

  // 启动生产计划列表定时器
  const startPlanListTimer = () => {
    if (planListTimer) {
      clearInterval(planListTimer)
      planListTimer = null
    }
    
    // 立即获取数据
    getProductionPlanList()
    
    // 使用 setTimeout 替代 setInterval，避免数据请求重叠
    const scheduleNextUpdate = () => {
      planListTimer = setTimeout(async () => {
        await getProductionPlanList()
        scheduleNextUpdate()
      }, 5000)
    }
    
    scheduleNextUpdate()
    console.log('生产计划列表定时器已启动，间隔：5秒')
  }
  </script>
  

  <style scoped>
  .smart-screen {
    width: 100%;
    min-width: 1440px;
    min-height: 100vh;
    color: #fff;
    position: relative;
    overflow-y: auto;
    overflow-x: auto;
    background: linear-gradient(-45deg, #001529, #002a4a, #003366, #001529);
    background-size: 400% 400%;
    animation: gradientBG 15s ease infinite;
  }
  
  @keyframes gradientBG {
    0% {
      background-position: 0% 50%;
    }
    50% {
      background-position: 100% 50%;
    }
    100% {
      background-position: 0% 50%;
    }
  }
  
  .smart-screen::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: 
      repeating-linear-gradient(45deg, 
        rgba(0,240,255,0.03) 0px, 
        rgba(0,240,255,0.03) 1px,
        transparent 1px, 
        transparent 15px
      ),
      repeating-linear-gradient(-45deg, 
        rgba(0,240,255,0.03) 0px, 
        rgba(0,240,255,0.03) 1px,
        transparent 1px, 
        transparent 15px
      );
    pointer-events: none;
  }
  
  .smart-screen::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: 
      radial-gradient(
        circle at 50% 50%,
        rgba(0,240,255,0.1) 0%,
        transparent 50%
      );
    opacity: 0.5;
    animation: pulse 4s ease-in-out infinite;
    pointer-events: none;
  }
  
  @keyframes pulse {
    0% {
      opacity: 0.3;
      transform: scale(0.95);
    }
    50% {
      opacity: 0.6;
      transform: scale(1.05);
    }
    100% {
      opacity: 0.3;
      transform: scale(0.95);
    }
  }
  
  .bg-decoration {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(90deg, 
      rgba(0,21,41,0) 0%,
      rgba(0,21,41,0.9) 20%,
      rgba(0,21,41,0.9) 80%,
      rgba(0,21,41,0) 100%
    );
    z-index: 1;
    padding: 0 20px;
    max-width: 1920px;
    margin: 0 auto;
    box-sizing: border-box;
    border-bottom: 1px solid rgba(0,240,255,0.2);
  }
  
  .left-decoration,
  .right-decoration {
    width: 300px;
    height: 100%;
    position: relative;
    overflow: hidden;
  }
  
  .left-decoration::before,
  .right-decoration::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg,
      rgba(0,240,255,0) 0%,
      rgba(0,240,255,0.5) 50%,
      rgba(0,240,255,0) 100%
    );
    transform: translateY(-50%);
  }
  
  .left-decoration::after,
  .right-decoration::after {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    background: repeating-linear-gradient(90deg,
      rgba(0,240,255,0.1) 0px,
      rgba(0,240,255,0.1) 2px,
      transparent 2px,
      transparent 10px
    );
  }
  
  .right-decoration {
    transform: scaleX(-1);
  }
  
  .center-decoration {
    font-size: 24px;
    font-weight: bold;
    color: #00f0ff;
    text-shadow: 0 0 10px rgba(0,240,255,0.5);
    padding: 0 40px;
    white-space: nowrap;
    position: relative;
    animation: textGlow 4s ease-in-out infinite;
  }
  
  @keyframes textGlow {
    0% {
      text-shadow: 0 0 10px rgba(0,240,255,0.5);
    }
    50% {
      text-shadow: 0 0 20px rgba(0,240,255,0.8);
    }
    100% {
      text-shadow: 0 0 10px rgba(0,240,255,0.5);
    }
  }
  
  .center-decoration::before,
  .center-decoration::after {
    content: '';
    position: absolute;
    top: -10px;
    bottom: -10px;
    width: 2px;
    background: linear-gradient(180deg,
      rgba(0,240,255,0) 0%,
      rgba(0,240,255,0.5) 50%,
      rgba(0,240,255,0) 100%
    );
  }
  
  .center-decoration::before {
    left: 0;
  }
  
  .center-decoration::after {
    right: 0;
  }
  
  .header {
    position: relative;
    z-index: 1;
    padding: 70px 20px 20px;
    display: flex;
    justify-content: flex-end;
    max-width: 1920px;
    margin: 0 auto;
    box-sizing: border-box;
  }
  
  .time {
    font-size: 18px;
    color: #00f0ff;
    background: rgba(0,21,41,0.6);
    padding: 8px 15px;
    border-radius: 4px;
    border: 1px solid #0a4cd1;
  }
  
  .content {
    position: relative;
    z-index: 1;
    display: grid;
    grid-template-columns: 400px 1fr 400px;
    gap: 20px;
    padding: 0 20px 20px;
    min-height: calc(100vh - 160px);
    margin: 0 auto;
    max-width: 1920px;
  }
  
  .left-section,
  .center-section,
  .right-section {
    display: flex;
    flex-direction: column;
    gap: 20px;
    min-width: 0; /* 防止子元素溢出 */
  }
  
  .chart-box {
    background: rgba(0, 21, 41, 0.8);
    border: 1px solid rgba(0,240,255,0.3);
    border-radius: 4px;
    padding: 15px;
    height: 360px;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: hidden;
    animation: borderGlow 4s ease-in-out infinite;
  }
  
  @keyframes borderGlow {
    0% {
      border-color: rgba(0,240,255,0.3);
      box-shadow: 0 0 10px rgba(0,240,255,0.1);
    }
    50% {
      border-color: rgba(0,240,255,0.6);
      box-shadow: 0 0 20px rgba(0,240,255,0.2);
    }
    100% {
      border-color: rgba(0,240,255,0.3);
      box-shadow: 0 0 10px rgba(0,240,255,0.1);
    }
  }
  
  .chart-box::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg, 
      rgba(0,240,255,0) 0%,
      rgba(0,240,255,0.5) 50%,
      rgba(0,240,255,0) 100%
    );
    animation: scanline 4s linear infinite;
  }
  
  @keyframes scanline {
    0% {
      transform: translateY(-100%);
      opacity: 0;
    }
    50% {
      opacity: 1;
    }
    100% {
      transform: translateY(360px);
      opacity: 0;
    }
  }
  
  .center-section .chart-box:nth-child(2) {
    height: calc(100vh - 460px);
    min-height: 520px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  
  .scroll-table-container {
    flex: 1;
    overflow: hidden;
    margin-top: 15px;
    position: relative;
    height: calc(100vh - 520px);
    min-height: 400px;
  }
  
  .chart-box h3 {
    margin: 0 0 20px 0;
    color: #00f0ff;
    font-size: 16px;
  }
  
  .chart {
    height: 300px;
    width: 100%;
  }
  
  .progress-info {
    margin-top: 15px;
    background: rgba(10, 76, 209, 0.1);
    padding: 12px;
    border-radius: 4px;
  }
  
  .progress-info p {
    margin: 6px 0;
    font-size: 13px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .progress-info p span {
    color: #00f0ff;
    font-weight: bold;
  }
  
  .team-info {
    background: rgba(10, 76, 209, 0.1);
    padding: 12px;
    border-radius: 4px;
    position: relative;
  }
  
  .team-info p {
    margin: 8px 0;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    line-height: 24px;
  }
  
  .team-info p span {
    color: #00f0ff;
    font-weight: 500;
  }
  
  .scroll-table-container {
    height: 480px;
    overflow: hidden;
    margin-top: 15px;
    position: relative;
  }
  
  .plan-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    border: 1px solid #0a4cd1;
    border-radius: 4px;
    table-layout: fixed;
    position: absolute;
    left: 0;
    height: 470px;
  }
  
  .plan-table thead {
    position: sticky;
    top: 0;
    z-index: 2;
    background: rgba(0, 21, 41, 0.95);
    display: table;
    width: 100%;
  }
  
  .plan-table tbody {
    position: relative;
    transition: none;
    display: block;
  }
  
  .plan-table tbody tr {
    height: 41px;
    transition: background-color 0.3s ease;
    display: table;
    width: 100%;
  }
  
  .status {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 4px;
    font-size: 12px;
  }
  
  .status.completed {
    color: #52c41a;
    background: rgba(82, 196, 26, 0.1);
  }
  
  .status.processing {
    color: #00f0ff;
    background: rgba(0, 240, 255, 0.1);
  }
  
  .status.pending {
    color: #faad14;
    background: rgba(250, 173, 20, 0.1);
  }
  
  .exception-list {
    height: 360px;
    overflow: auto;
  }
  
  .exception-item {
    padding: 12px;
    border-bottom: 1px solid #0a4cd1;
    background: rgba(10, 76, 209, 0.1);
    margin-bottom: 8px;
    border-radius: 4px;
  }
  
  .exception-item .time {
    color: #00f0ff;
    margin-right: 12px;
    font-size: 13px;
  }
  
  .exception-item .type {
    color: #ff4d4f;
    margin-right: 12px;
    font-weight: bold;
    font-size: 13px;
  }
  
  .exception-item .description {
    display: block;
    margin-top: 6px;
    color: #fff;
    opacity: 0.8;
    font-size: 13px;
  }
  
  .info-box {
    background: rgba(0, 21, 41, 0.8);
    border: 1px solid #0a4cd1;
    border-radius: 4px;
    padding: 15px;
    min-height: 300px;
  }
  
  .info-box h3 {
    margin: 0 0 20px 0;
    color: #00f0ff;
    font-size: 16px;
  }
  
  .scroll-list {
    padding-right: 10px;
  }
  
  :deep(.echarts-tooltip) {
    background: rgba(0, 21, 41, 0.9) !important;
    border: 1px solid #0a4cd1 !important;
  }
  
  /* 确保页面在小屏幕上也能完整显示 */
  @media screen and (max-height: 900px) {
    .chart-box {
      height: 260px;
    }
    
    .chart {
      height: 200px;
    }
    
    .scroll-table-container,
    .exception-list {
      height: 300px;
    }
    
    .content {
      gap: 15px;
    }
    
    .left-section,
    .center-section,
    .right-section {
      gap: 15px;
    }
  }
  
  .order-id {
    font-family: monospace;
    text-align: left;
    padding-left: 15px !important;
    color: #00f0ff !important;
    font-size: 14px;
  }
  
  .plan-table th,
  .plan-table td {
    padding: 12px 8px;
    text-align: center;
    border-bottom: 1px solid rgba(10, 76, 209, 0.3);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  /* 设置列宽 */
  .plan-table th:nth-child(1),
  .plan-table td:nth-child(1) {
    width: 180px;  /* 订单号列加宽 */
  }
  
  .plan-table th:nth-child(2),
  .plan-table td:nth-child(2) {
    width: 100px;
  }
  
  .plan-table th:nth-child(3),
  .plan-table td:nth-child(3),
  .plan-table th:nth-child(4),
  .plan-table td:nth-child(4) {
    width: 160px;
  }
  
  .plan-table th:nth-child(5),
  .plan-table td:nth-child(5) {
    width: 100px;
  }
  
  .plan-table th:nth-child(6),
  .plan-table td:nth-child(6) {
    width: 80px;
  }
  
  .scroll-table-container {
    height: 300px;
    overflow: auto;
    margin-top: 15px;
  }
  
  .scroll-table-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  
  .scroll-table-container::-webkit-scrollbar-thumb {
    background: #0a4cd1;
    border-radius: 3px;
  }
  
  .scroll-table-container::-webkit-scrollbar-track {
    background: rgba(10, 76, 209, 0.1);
    border-radius: 3px;
  }
  
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  .team-info {
    animation: fadeInUp 0.5s ease-out;
  }
  </style>

  
  